package com.spring.cloud.practice.demo.springboot.shiro.realm;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

/**
 * <b><code>CustomRealm</code></b>
 * <p/>
 * Description
 * <p/>
 * <b>Creation Time:</b> 21-3-24 下午3:14.
 *
 * @author huanghuayan
 * @since spring-cloud-demo
 */
@Component
public class CustomRealm extends AuthorizingRealm {


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> set = new HashSet<>();
        set.add("user:show");
        set.add("user:admin");
        info.setStringPermissions(set);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("-------------身份认证------------");
        String username = (String) authenticationToken.getPrincipal();
        String password = new String((char[]) authenticationToken.getCredentials());
        String db_passwd = new SimpleHash("md5", "123", ByteSource.Util.bytes(username), 2).toHex();
        if (username == null) {
            throw new AccountException("用户名不正确");
        } else if (!password.equals("123")) {
            throw new AccountException("密码不正确");
        }
        return new SimpleAuthenticationInfo(username, db_passwd, ByteSource.Util.bytes((username)), getName());
    }
}
